package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseSingleButtonDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.SubmitFileOriginal.SubmitFileContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.util.HashMap;
import org.apache.http.Header;
import org.json.JSONException;

public class DetailSubmitFileFragment extends Fragment {

  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.DetailSubmitFileFragment.EXTRA_CONTENT";
  private static final int REQUEST_ADDEXTRA = 1;//附件
  protected static final int REQUEST_RENAME = 2;//重命名
  protected static final int REQUEST_SUBMIT = 3;//提交
  protected String mFilePath = "";//文件本地路径
  protected String mfileName = "";
  private String fileName = "";
  protected String selcurFile = "";//文件上传服务器返回路径
  private TextView mTvfileName;
  private TextView mTvfileSubmit;
  private ImageView mIbfileSubmit;
  //    private TextView mTvifSubmit;
  private EditText mEtremark;
  protected RadioGroup rgifSubmit;
  protected RadioButton rbtrueSubmit;
  protected RadioButton rbfalseSubmit;

  private SubmitFileContent content;
  private BaseVolleyActivity mActivity;

  private String dataStatus = "";

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.submitFileDetail);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    mActivity = (BaseVolleyActivity) getActivity();
    content = (SubmitFileContent) getArguments().getSerializable(EXTRA_CONTENT);
    fileName = content.getDataPath();
    mfileName = fileName;
    if (content.getDataPath() == null) {
      selcurFile = "";
    } else {
      selcurFile = content.getDataPath();
    }

    dataStatus = content.getDataStatus();
    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.menu_confirm, menu);
    if ("publish".equals(content.getDataStatus())) {
      menu.getItem(0).setEnabled(false).setVisible(false);
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      case R.id.menu_item_confirm:

        if ("new".equals(dataStatus)) {
          //提交文档
          //有附件时
          if (!TextUtils.isEmpty(mFilePath)) {
            volleyExtra();
          } else {
            volleyPostSave();
          }
        } else if ("publish".equals(dataStatus)) {
          DialogFragment dialog =
              BaseConfirmDialogFragment.newInstance(R.string.cannotEdit, R.string.restart_title);
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog.setTargetFragment(DetailSubmitFileFragment.this, REQUEST_SUBMIT);
          dialog.show(fm, "");
        }

        //			//提交文档
        //			//有附件时
        //			if (!TextUtils.isEmpty(mDocPath)) {
        //				volleyExtra();
        //			}else {
        //				volleyPostSave();
        //			}

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_submit_file, container, false);
    initData(v);
    return v;
  }

  private void initData(View v) {
    mTvfileName = (TextView) v.findViewById(R.id.tv_fileName);
    mTvfileSubmit = (TextView) v.findViewById(R.id.tv_fileSubmit);
    mIbfileSubmit = (ImageView) v.findViewById(R.id.ib_fileSubmit);
    //        mTvifSubmit = (TextView) v.findViewById(R.id.tv_ifSubmit);
    mEtremark = (EditText) v.findViewById(R.id.et_remark);

    mTvfileName.setText(content.getProjectpropName());
    mEtremark.setText(content.getRemark());

    //RadioButton点击事件，是否冲抵借款
    rgifSubmit = (RadioGroup) v.findViewById(R.id.rg_isSubmit);
    rbfalseSubmit = (RadioButton) v.findViewById(R.id.rb_false_submit);
    rbtrueSubmit = (RadioButton) v.findViewById(R.id.rb_true_submit);

    if ("new".equals(content.getDataStatus())) {
      rbtrueSubmit.setChecked(false);
      rbfalseSubmit.setChecked(true);
    }
    if ("publish".equals(content.getDataStatus())) {
      rbtrueSubmit.setChecked(true);
      rbfalseSubmit.setChecked(false);
      mIbfileSubmit.setVisibility(View.INVISIBLE);
      rbtrueSubmit.setEnabled(false);
      rbfalseSubmit.setEnabled(false);
      mEtremark.setEnabled(false);
    }
    rgifSubmit.setOnCheckedChangeListener(new OnCheckedChangeListener() {

      @Override public void onCheckedChanged(RadioGroup arg0, int arg1) {
        switch (arg1) {
          case R.id.rb_false_submit:
            dataStatus = "new";
            break;
          case R.id.rb_true_submit:
            dataStatus = "publish";
            break;

          default:
            break;
        }
      }
    });

    if (!TextUtils.isEmpty(content.getDataPath())) {
      //附件
      mTvfileSubmit.setText(content.getDataPath());
      //点击附件名，下载附件
      mTvfileSubmit.setOnClickListener(new OnClickListener() {

        @Override public void onClick(View v) {
          ExtraDownLoadDialogFragment dialog = null;
          if (TextUtils.isEmpty(mFilePath)) {
            dialog = ExtraDownLoadDialogFragment.newInstance("", selcurFile);
          } else {
            dialog = ExtraDownLoadDialogFragment.newInstance(mFilePath, "");
          }

          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog.show(fm, "");
        }
      });
    }
    mIbfileSubmit.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        DialogFragment dialog = ExtraUpLoadDialogFragment.newInstance(mFilePath);
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(DetailSubmitFileFragment.this, REQUEST_ADDEXTRA);
        dialog.show(fm, "");
      }
    });
  }

  //附件上传
  private void volleyExtra() {

    //		new FileNetWorkUtil(getActivity()).upLoadFile(mDocPath, ApiConst.URL_UPLOAD_FILE,"", "r_expense_inexp_main", content.getId(), new myUpLoadHandler(), false);

    new FileNetWorkUtil(getActivity()).upLoadFile(mFilePath, ApiConst.URL_UPLOAD_FILE, null,
        "projectManagement", "DD_PROJECTSTAGE_DOC_SUB", content.getId(), new myUpLoadHandler(),
        false);
  }

  private class myUpLoadHandler extends AsyncHttpResponseHandler {
    @Override public void onStart() {
      MyUtils.showDialogLoading(getActivity());
      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      //		MyUtils.dismissDialog();
      Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      MyUtils.dismissDialog();
      LogUtil.i("arg2==" + new String(arg2));
      try {

        SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
        if (result == null) {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.wrong_data, Toast.LENGTH_SHORT).show();
        }
        if (result != null && result.getResult() != null && result.getResult().equals("1")) {
          //					Toast.makeText(getActivity(), R.string.fileUploadSuccess, Toast.LENGTH_SHORT).show();
          // 上传成功,再上传数据
          selcurFile = result.getMessage().toString();
          selcurFile = selcurFile.replace("\\", "/");
          LogUtil.i("selcurFile==" + selcurFile);
          volleyPostSave();
        } else {
          MyUtils.dismissDialog();
          DialogFragment dialog = null;
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog = BaseSingleButtonDialogFragment.newInstance(R.string.rename_file,
              R.string.restart_title);
          dialog.setTargetFragment(DetailSubmitFileFragment.this, REQUEST_RENAME);
          dialog.show(fm, "");
        }
      } catch (JsonSyntaxException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      } catch (NotFoundException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      }
    }
  }

  //文档提交
  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_SUBMIT_FILE);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("id", content.getId());
    params.put("dataPath", selcurFile);
    //		params.put("dataPath", null);
    params.put("dataStatus", dataStatus);
    params.put("remark", mEtremark.getText().toString());
    LogUtil.i("文档提交params===" + params.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.wrong_data);
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_ADDEXTRA) {

      String result = data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_RESULT);
      if (ExtraUpLoadDialogFragment.VALUE_CLEAR.equalsIgnoreCase(result)) {
        clearExtraFile();
      } else {

        mFilePath = result;
        LogUtil.i("mDocPath===" + mFilePath);
        if (mFilePath != null) {
          mfileName = FileUtil.getFileNameByFilePath(mFilePath);
          //					String fileName = FileUtil.getFileNameByFilePath(mDocPath);
          //					String[] names =fileName.split("\\.");
          //					mfileName =names[names.length-2]+"."+names[names.length-1];
          mTvfileSubmit.setText(mfileName);
        }
      }
    }
    if (requestCode == REQUEST_RENAME) {

    }
    if (requestCode == REQUEST_SUBMIT) {
      //提交文档
      //有附件时
      if (!TextUtils.isEmpty(mFilePath)) {
        volleyExtra();
      } else {
        volleyPostSave();
      }
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public void clearExtraFile() {
    mFilePath = "";
    mfileName = "";
    mTvfileSubmit.setText("");
  }

  public static DetailSubmitFileFragment newInstance(SubmitFileContent content) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    DetailSubmitFileFragment fragment = new DetailSubmitFileFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
